import 'dart:async';
import 'dart:convert' as convert;
import 'dart:convert';
import 'dart:math';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/shims/dart_ui_real.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/config/event_bus.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/main/logic.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:yp/utils/util.dart';

import 'state.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class MallLogic extends GetxController with SingleGetTickerProviderMixin {
  // final MainAppLogic MainAppLogics = Get.put(MainAppLogic());
  final MainLogic mainLogic = Get.put(MainLogic());
  final state = MallState();

  AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  /// 定位信息
  var locationResult = {}.obs;

  /// 是否正在定位
  var isPositioning = false.obs;

  @override
  void onInit() async {
    super.onInit();

    var addressParams = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };

    getCurrentLocationInfo(success: (data) {
      var localLocation = SpUtil.getObject(Config.USER_CURRENT_LOCATION);
      var addressInfo = data['addressInfo'];
      if (localLocation["userSelectAddress"] == null) {
        changeSelectAddress(addressInfo);
      }
    });

    state.isChangeShop = SpUtil.getInt(Config.IS_CHANGE_SHOP) ?? 0;
    Map<String, dynamic> params = {
      "shop_id": SpUtil.getInt("storeShopNum"),
      "type": "defword"
    };

    Api.getRealTimeHotSearchList(params).listen((event) {
      print("获取热搜列表========：$event");
      if (event["code"] == 0) {
        if (event["word_title"] != null) {
          // state.hotSearchTitle = event["word_title"];
        }
        if (event["word"] != null) {
          List list = event["defword"];
          int len = list.length;
          int rand = Random().nextInt(len);
          state.keyword = list[rand]["defword_name"];
          // state.realTimeSearchList = list;
        }
        update();
      }
    }, onDone: () {});
    if (!kIsWeb) {
      eventBus.on<InitPackage>().listen((event) {
        requestLocationPermission().then((value) {
          if (value) {
            //  AMapFlutterLocation.setApiKey(
            //     Config.AMap_andriod, Config.AMap_ios_get);
            // _locationPlugin = AMapFlutterLocation();

            print("授权通过，开始定位~~~~~~~~~~~1111");
            startLocation();
          } else {
            print("授权不通过，不会定位了~~~~~~~~~~~22222");
          }
        });
      });

      /// 注册定位结果监听
      _locationPlugin.onLocationChanged().listen((Map<String, Object> result) {
        isPositioning.value = false;
        print("定位结果监听:$result");
        if (result != null &&
            result.length > 0 &&
            result["errorCode"] == null &&
            result["errorInfo"] == null) {
          locationResult.value["AMapResult"] = result;
          surroundingSearch(null);
        } else {
          locationResult.value["AMapResult"] = {};
        }
        SpUtil.putObject(Config.USER_CURRENT_LOCATION, locationResult);
        update();

        onReady();
      });

      bool isAgree = SpUtil.getBool("isAgree", defValue: false);
      if (isAgree) {
        requestLocationPermission().then((value) {
          if (value) {
            print("授权通过，开始定位~~~~~~~~~~~");
            startLocation();
          } else {
            print("授权不通过，不会定位了~~~~~~~~~~~");
          }
        });
      }

      startLocation();
    } else {
      isPositioning.value = false;
      locationResult.value["AMapResult"] = {
        'callbackTime': '2021-12-23 11:00:34',
        'locationTime': '2021-12-23 11:00:33',
        'locationType': 6,
        'latitude': 22.683611,
        'longitude': 114.228577,
        'accuracy': 550.0,
        'altitude': 0.0,
        'bearing': 0.0,
        'speed': 0.0,
        'country': '中国',
        'province': '广东省',
        'city': '深圳市',
        'district': '龙岗区',
        'street': '龙岗大道',
        'streetNumber': '地铁3号线大运站A出口',
        'cityCode': '0512',
        'adCode': '320583',
        'address': '广东省深圳市龙岗区龙岗大道地铁3号线大运站A出口',
        'description': '大运软件小镇'
      };

      // if (data != null) {
      //   locationResult.value["AMapResult"] = data;
      // }
      surroundingSearch(null);
      SpUtil.putObject(Config.USER_CURRENT_LOCATION, locationResult);
      update();
    }
  }

  @override
  void onReady() {
    super.onReady();
    signInClick();
    state.dx = 15;
    state.dy = setHeight(1334) - 70 - 56.0;
    var params = {
      'hash_code': Config.hashCode1,
    };
    var closeAdvertise = SpUtil.getBool('closeAdvertise') ?? false;
    if (!closeAdvertise) fetchAdvertise();

    Api.pingTaiZongDian(params).listen((event) {
      print('===========  首页  ===========  $event');
      if (event['code'] == 0) {
        List list = event['express_shops'];
        if (list.length > 0) {
          Map<String, dynamic> expressMap = list[0];
          SpUtil.putInt('storeShopNum', expressMap['ec_shop_num_id']); //  门店id
          SpUtil.putInt(
              'storeUnitNum', expressMap['sub_unit_num_id']); //  门店线下id
          if (state.isChangeShop == 0 &&
              SpUtil.getObject(Config.GET_SHOP_INFO) == null) {
            getAndGoThirdShop();
          }

          /// 店铺收藏列表
          if (state.isChangeShop == 1) {
            getColoectShopList();
          }
          configurationInformation();
        }
      }
      update();
    }, onError: (error) {
      print('+++++****** 首页 ++++++++++++ 失败 ++++++++++++ error = $error');
    });

    if (kIsWeb) {
      Future.delayed(Duration(seconds: 15), () async {
        //改到15s后执行，这个方法加载过早，会导致后边的代码无法执行，首页白屏
        var data = await fetchH5Location();

        print("datadatadatadata=== ${data}");

        if (data != null) {
          Map<String, dynamic> params = {
            "use_platform": 2,
            "maplocation_x": data['longitude'],
            "maplocation_y": data['latitude'],
            // "city": city,
            // "key_words": keywords
          };

          Api.surroundingSearch(params).listen((event) {
            // toast("经度:${data['latitude']}");
            print("周边搜索==========$event");
            if (event["code"] == 0 && event["address"] != null) {
              var location = jsonDecode(event['address']['location_name']);
              data['province'] = location['pname'];
              data['city'] = location['cityname'];
              data['district'] = location['adname'];
              data['street'] = location['name'];
              data['streetNumber'] = location['name'];
              data['description'] = location['name'];
              data['adCode'] = location['adcode'];
              data['cityCode'] = location['citycode'];

              if (data != null) {
                locationResult.value["AMapResult"] = data;
              }
              surroundingSearch(null);
              SpUtil.putObject(Config.USER_CURRENT_LOCATION, locationResult);
              update();
            }
          });
        }
      });
    }
  }

  // 签到数据
  void signInClick() {
    individualizationConfigure();
    var rulesParams = {
      'access_token': SpUtil.getString('token'),
      'page': 1,
      'page_size': 10,
    };
    Api.signInRules(rulesParams).listen((event) {
      print('签到规则 返回数据  成功  event = $event');
      if (event['code'] == 0) {
        List list = event['sign_in_rule_infos'];
        if (list.length > 0) {
          if (list[0]['open_sign'] == 1) {
            state.signInBool = true;
          } else {
            state.signInBool = false;
          }
        }
      }
      update();
    }, onError: (error) {
      print('签到规则 返回数据  失败  error = $error');
    });
  }

  // 获取会员中心个性化配置
  void individualizationConfigure() {
    String shopNumId = '';
    if (SpUtil.getObject(Config.GET_SHOP_INFO) != null &&
        SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'] != null) {
      print(' 获取会员中心个性化配置 获取会员中心个性化配置  1111111111111111');
      shopNumId = SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'].toString();
    } else {
      print(' 获取会员中心个性化配置 获取会员中心个性化配置  2222222222222222');
      shopNumId = SpUtil.getInt('storeShopNum').toString();
    }
    var paramsDiy = {
      "ec_shop_num_id":
          shopNumId, // SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    };
    Api.personalizedConfiguration(paramsDiy).listen((event) {
      if (event['code'] == 0) {
        if (event['personal_config_shop_image'] != null) {
          if (event['personal_config_shop_image']['enter_img'] != null) {
            if (event['personal_config_shop_image']['enter_img']['home_page'] !=
                null) {
              state.signInImage =
                  event['personal_config_shop_image']['enter_img']['home_page'];
            }
          }
        }
      }
      update();
    });
  }

  /// 首页爆屏广告逻辑
  fetchAdvertise() {
    SpUtil.putBool("closeAdvertise", true);
    var shopInfo = SpUtil.getObject(Config.GET_SHOP_INFO);

    var params = {
      "page_num": 1,
      "page_size": 3,
      "tmpl_platform_type": "2",
      "ec_shop_num_id": shopInfo != null
          ? shopInfo['shop_id']
          : SpUtil.getInt('storeShopNum'),
      "tmpl_type": "5",
      "tmpl_status": "1"
    };

    Api.getAdvertiseImg(params).listen((event) {
      print(event['list']);
      if (event['code'] == 0 &&
          event['list'] != null &&
          event['list'].length > 0) {
        var tmlId = event['list'][0]['tmpl_num_id'];
        var modelList = event['list'];

        if (!modelList[0]['enabled']) {
          state.advertiseImgData = {};
          return;
        }

        fetchAdvertiseImg(tmlId.toString());
      } else {
        print("爆屏页没有数据");
      }
    });
  }

// 1.调用这个接口获取爆屏模板tmpl_num_id；ykcloud.home.mobile.tmpl.instance.get；
// 2.调用这个接口获取爆屏数据：com.gb.soa.omp.decorate.service.impl.EcSysShopServiceImpl.getTmplInstanceDetail,
// widgets_sign==7时，是爆屏广告；
// widgets_sign==10时，是爆屏优惠券和红包；
// 3.等于widgets_sign==10时，需要调用这个接口获取优惠券ykcloud.card.search.coupon.claim
// 4.领取优惠券接口gb.scrm.couponruleCard.memberReceiveCouponfor
  fetchAdvertiseImg(String tmlId) {
    var shopInfo = SpUtil.getObject(Config.GET_SHOP_INFO);

    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "tmpl_num_id": tmlId,
      "ec_shop_num_id": shopInfo != null
          ? shopInfo['shop_id']
          : SpUtil.getInt('storeShopNum'),
    };

    Api.channelPageTemplate(params).listen((event) {
      if (event['code'] == 0) {
        if (!event['instance']['enabled']) {
          state.advertiseImgData = {};
          return;
        }
        if (event['instance']['data'] == null) {
          state.advertiseImgData = {};
          return;
        }

        List tmpList = event['instance']['data'];
        var imgData, couponAds;

        tmpList.forEach((element) {
          if (element["widgets_sign"] == 7) {
            imgData = element;
          }
          if (element["widgets_sign"] == 10) {
            couponAds = element;
          }
        });

        // 显示优惠券弹框
        // update();
        print("EcSysShopServiceImpl coupon======${imgData}");
        // var imgData = event['instance']['data'][0];
        if (imgData == null) {
          state.advertiseImgData = {};
          return;
        }
        var imgDataList = convert.jsonDecode(imgData['widgets_data_params']);
        var isShowCom = imgData['widgets_data_status'];

        if (couponAds['widgets_sign'] == 10 &&
            couponAds['widgets_data_status'] == 1) {
          var styleIds = [];
          state.widgets_data_id = couponAds["widgets_data_id"];
          if (couponAds['style'] != null && couponAds['style'].length > 0) {
            couponAds['style'].forEach(
                (styleItem) => {styleIds.add(styleItem['style_num_id'])});
            couponAds['couponlist'] = [];
            if (styleIds != null && styleIds.length > 0) {
              print("-------------获取爆屏优惠券1----------$styleIds-----------");

              Api.fetchNewCouponList({
                "usr_num_id": SpUtil.getInt('empeNumId'),
                "activityids": styleIds
              }).listen((event) {
                print("-------------获取爆屏优惠券2-----------$event----------");
                var couponDataList =
                    convert.jsonDecode(couponAds['widgets_data_params']);
                state.couponData = {
                  'width': couponDataList['width'],
                  'height': couponDataList['height'],
                  'pictures': couponDataList['pictures'],
                  'widgets_data_id': imgData['widgets_data_id'],
                };
                if (event["card_tickets"] != null &&
                    event["card_tickets"].length > 0) {
                  if (event["card_tickets"][0]["relation"] != 1) {
                    state.couponList = event["card_tickets"];
                  }
                }
                if (state.advertiseImgData == null &&
                    state.couponList.length > 0) {
                  showCouponDialog();
                }
                update();
              });
            }
          }
        }
        if (imgData['widgets_sign'] == 7 &&
            imgData['widgets_data_status'] == 1) {
          state.advertiseImgData = {
            'width': imgDataList['width'],
            'height': imgDataList['height'],
            'pictures': imgDataList['pictures'],
            'widgets_data_id': imgData['widgets_data_id'],
            'is_show_way': imgDataList['pictures'][0]['is_show_way'],
            'couponlist': imgData['couponlist'],
            'isShowCom': isShowCom
          };

          print(
              "EcSysShopServiceImpl coupon1111======${state.advertiseImgData}");

          state.isShowAdvertise = true;
          if (imgDataList['pictures'][0]['pic_url'] == null) {
            state.isShowAdvertise = false;
          }

          // 弹窗显示
          if (state.isShowAdvertise) {
            // return;
            showDialog(
              context: Get.context,
              barrierDismissible: false,
              builder: (BuildContext context) {
                return new Material(
                  type: MaterialType.transparency, //透明类型
                  child: Center(
                    child: Container(
                      width: double.parse(
                          state.advertiseImgData['width'].toString()),
                      height: double.parse(
                              state.advertiseImgData['height'].toString()) +
                          25.0,
                      child: Container(
                        child: Column(
                          children: [
                            InkWell(
                              child: Container(
                                child: Image.network(
                                  imgDataList['pictures'][0]['pic_url'],
                                  width: double.parse(state
                                      .advertiseImgData['width']
                                      .toString()),
                                  height: double.parse(state
                                      .advertiseImgData['height']
                                      .toString()),
                                  fit: BoxFit.fill,
                                ),
                              ),
                              onTap: () {
                                Get.back();
                                print('跳转到商品详情页具体页面...');
                                var linktype =
                                    state.advertiseImgData['pictures'][0]
                                        ['linktype'];
                                var linktarget =
                                    state.advertiseImgData['pictures'][0]
                                        ['linktarget'];
                                jump(url: linktype.toString(), model: {
                                  "linktype": linktype,
                                  "linktarget": linktarget,
                                });
                                // Get.toNamed(RouteConfig.goodsDetail, arguments: {
                                //     'itemNumId': imgDataList['pictures'][0]['linktarget'].toString(),
                                //     'styleNumId': '2',
                                //     'shopId': SpUtil.getInt('storeShopNum').toString(),
                                //     // 'cat1Id': arguments['cat1_id'],
                                // 'typeIndex': imgDataList['pictures'][0]['is_pre_sale'],
                                // });
                                // switch (state.advertiseImgData['pictures'][0]
                                //     ['linktype']) {
                                //   case 2:
                                //     print('跳转到详情页');
                                //     var params = {
                                //       // 'shop_id': SpUtil.getInt('storeShopNum'),
                                //       "shop_id": SpUtil.getObject(
                                //           Config.GET_SHOP_INFO)['shop_id'],
                                //       'prv_num_id': '',
                                //       'city_num_id': '',
                                //       'city_area_num_id': '',
                                //       'style_num_id': state
                                //           .advertiseImgData['pictures'][0]
                                //               ['linktarget']
                                //           .toString(),
                                //       'item_num_id': state
                                //           .advertiseImgData['pictures'][0]
                                //               ['linktarget']
                                //           .toString()
                                //     };
                                //     Api.goodsDetail(params).listen((event) {
                                //       if (event['code'] == 0) {
                                //         print('----------商品详情信息------------');
                                //         print(event);
                                //       }
                                //     });
                                //     break;
                                // }
                                print(state.advertiseImgData);
                              },
                            ),
                            InkWell(
                              child: Icon(
                                Icons.close_outlined,
                                color: Colors.white,
                              ),
                              onTap: () {
                                // 关闭弹窗
                                Navigator.pop(context);
                                if (state.couponData != null &&
                                    state.couponList.length > 0) {
                                  showCouponDialog();
                                }
                              },
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                );
              },
            );
          }
        }
      }
    });
  }

  showCouponDialog() {
    showDialog(
        context: Get.context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return Material(
            type: MaterialType.transparency,
            child: Center(
              child: Container(
                width: double.parse(state.couponData['width'].toString()),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(
                      child: Image.network(
                        state.couponData['pictures'][0]['pic_url'],
                        width:
                            double.parse(state.couponData['width'].toString()),
                        height:
                            double.parse(state.couponData['height'].toString()),
                        fit: BoxFit.fill,
                      ),
                    ),
                    Container(
                      width: double.parse(state.couponData['width'].toString()),
                      color: Color(0xffC71D1F),
                      padding: EdgeInsets.only(
                        left: 15,
                        right: 15,
                        bottom: 50,
                      ),
                      child: Column(
                        children: state.couponList.map((e) {
                          return Container(
                            padding: EdgeInsets.all(10),
                            decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(5),
                            ),
                            margin: EdgeInsets.only(top: 15),
                            child: Column(
                              children: [
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text(
                                      "${e['title']}",
                                      style: TextStyle(
                                          color: Colors.black, fontSize: 13),
                                    ),
                                    if (e['type_id'] == 0)
                                      Text(
                                        "${e['face_value']*100/1000}折",
                                        style: TextStyle(
                                            color: Colors.black, fontSize: 13),
                                      ),
                                    if (e['type_id'] == 1)
                                      Text(
                                        "￥${e['face_value']}",
                                        style: TextStyle(
                                            color: Colors.black, fontSize: 13),
                                      ),
                                    if (e['type_id'] == 2)
                                      Text(
                                        "${e['face_value'] != 0 ? '￥${e['face_value']}' : '免邮' }",
                                        style: TextStyle(
                                            color: Colors.black, fontSize: 13),
                                      ),
                                  ],
                                ),
                                SizedBox(height: 5),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    if (e["fixed_term"] == null)
                                      Text(
                                        "${DateFormat('yyyy.MM.dd').format(DateTime.parse(e['use_begin_date']))}-${DateFormat('yyyy.MM.dd').format(DateTime.parse(e['use_begin_end']))}",
                                        style: TextStyle(
                                            color: Colors.black54,
                                            fontSize: 12),
                                      ),
                                    if (e["fixed_term"] != null)
                                      Text(
                                        "自领券${e["fixed_term"]}日内",
                                        style: TextStyle(
                                            color: Colors.black54,
                                            fontSize: 12),
                                      ),
                                    if (e['least_cost'] == 0)
                                      Text(
                                        "无门槛",
                                        style: TextStyle(
                                            color: Colors.black, fontSize: 12),
                                      ),
                                    if (e['least_cost'] != 0)
                                      Text(
                                        "🈵️${e['least_cost'].toString().replaceAll('.0', '')}元使用",
                                        style: TextStyle(
                                            color: Colors.black, fontSize: 12),
                                      ),
                                  ],
                                ),
                              ],
                            ),
                          );
                        }).toList(),
                      ),
                    ),
                    GestureDetector(
                      onTap: () {
                        if (SpUtil.getInt('empeNumId') == 0) {
                          Get.toNamed(RouteConfig.mallLogin);
                          return;
                        }
                        var activityArray = [];
                        state.couponList.forEach((element) {
                          activityArray.add({"activityid": element["series"]});
                        });

                        var params = {
                          "use_platform": 2,
                          "usr_num_id": SpUtil.getInt('empeNumId'),
                          "access_token": SpUtil.getString('token'),
                          "coupon_batch_receives": activityArray,
                          "widgets_data_id": state.widgets_data_id,
                          //券来源
                          "relation": '爆屏页',
                          "qsource": 302
                        };
                        print("card.search.coupon.claim---$params");
                        // return;
                        Api.getAllCoupon(params).listen((event) {
                          if (event["code"] == 0) {
                            toast("领取成功");
                            Get.back();
                          } else {
                            if (!event["message"]
                                .toString()
                                .contains("会员卡号无效")) {
                              toast(event["message"]);
                            }
                          }
                        });
                      },
                      child: Container(
                        width: 200,
                        margin: EdgeInsets.only(top: 20),
                        padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          color: Color(0xffC71D1F),
                          borderRadius: BorderRadius.circular(100),
                        ),
                        child: Center(
                          child: Text(
                            "一键领取",
                            style: TextStyle(color: Colors.white),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: 40),
                    InkWell(
                      child: Icon(
                        Icons.close_outlined,
                        color: Colors.white,
                      ),
                      onTap: () {
                        // 关闭弹窗
                        Navigator.pop(context);
                      },
                    )
                  ],
                ),
              ),
            ),
          );
        });
  }

  /// 获取配置信息
  void configurationInformation() {
    var shopInfo = SpUtil.getObject(Config.GET_SHOP_INFO);
    var params = {
      'tmpl_platform_type': '2', //平台:2 APP, 3 小程序
      "ec_shop_num_id": shopInfo != null
          ? shopInfo['shop_id']
          : SpUtil.getInt('storeShopNum'), // 店铺ID
      'tmpl_type': '1', //页面类型 1频道页 2引导页  3活动页  4广告页  5爆屏页,6 分类页,7 百货页
    };
    Api.homeTemplate(params).listen((event) {
      print('hhhhhhhhhhhhhhhhh-$params');
      print('首页 配置信息  event = $event');
      if (event['code'] == 0) {
        if (event['instance'] != null) {
          // fetchAdvertiseImg("${event['instance']['tmpl_num_id']}");

          List list = event['instance']['data'];
          print('=============================');
          print(list);
          print(list.length);
          print(list[0]);
          print('=============================');
          if (event['instance']['data'] != null) {
            List list1 = [];
            for (int i = 0; i < list.length; i++) {
              var map = list[i];
              if (map['widgets_data_status'] == 1) {
                list1.add(map);
              }
            }
            state.templateList = list1;
            processingList();
          } else {
            state.templateList = [];
          }
        } else {
          toast('门店没有数据');
        }
      }
      update();
    });
  }

  void processingList() {
    state.goodsList = [];
    state.angleInformationList = [];
    state.couponsList = [];
    state.templateList.map((itemModel) {
      if (itemModel['widgets_sign'] == 4) {
        refreshList(dataMap: itemModel);
      }
      if (itemModel['widgets_sign'] == 8) {
        homeCoupon(dataMap: itemModel);
      }
    }).toList();
  }

  // 获取优惠券信息
  void channelPageTemplate() {
    var params = {
      'from_sign': 1, //死值,移动端专用
      // 'usr_num_id': SpUtil.getInt('empeNumId'),
      'tmpl_num_id':
          '21090900010008', //Get.arguments['linktarget'] ?? '', //模板ID
      // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    };
    Api.channelPageTemplate(params).listen((event) {
      print(' ===== 获取优惠券信息：=====   event = $event');
      if (event['code'] == 0) {
        List list = event['instance']['data'];
        list.forEach((element) {
          if (element['widgets_sign'] == 8) {
            print(
                '++++++++++  element[widgets_content] = ${element['widgets_content']}');
            print(
                '++++++++++  element[widgets_content] = ${element['widget']['widgets_content']}');
            var map = convert.jsonDecode(element['widgets_content']);
            print('++++++++++  map = $map');
            var mapData =
                convert.jsonDecode(element['widget']['widgets_content']);
            print('++++++++++  mapData = $mapData');
          }
        });
      }
      update();
    });
  }

  void refreshList({
    Map<String, dynamic> dataMap,
  }) {
    var map = convert.jsonDecode(dataMap['widgets_data_params']);
    var params = {
      'use_platform': '2',
      // 'shop_id': SpUtil.getInt('storeShopNum'),
      "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      'shop_num_id': dataMap['ec_shop_num_id'],
      'page_no': '1',
      // 'page_size': dataMap['nublayout'] == 'no'
      //     ? 12
      //     : (dataMap['nubnub'] == null || dataMap['nubnub'] == ''
      //         ? 12
      //         : dataMap['nubnub']),
      'page_size': dataMap['style'].length,
      'nublayout': map['nublayout'],
      'nubnub': map['nubnub'],
      'widgets_data_id': dataMap['widgets_data_id'],
      'sold_type': map['sold_type'],
      'access_token': SpUtil.getString('token'),
      'customer_type': 3,
      'user_num_id': SpUtil.getInt('empeNumId'),
      // 'prv_num_id': '',
      // 'city_num_id': '',
      // 'city_area_num_id': '',
    };
    Api.optionalGoods(params).listen((event) {
      // print('自购商品  $event');
      if (event['code'] == 0) {
        // if (dataMap['style'].length==8) {
        //   print(params);
        // }
        Map<String, dynamic> goodsMap = {
          'widgets_data_id': dataMap['widgets_data_id'],
          'listMap': event['lists'],
        };
        state.goodsList.add(goodsMap);
        List goodLists = [];
        List styleList = event['lists'];
        styleList.forEach((element) {
          goodLists.add('${element['default_item_num_id']}');
        });
        // print('***************** =============== goodsList = $goodsList');
        if (goodLists.length == 0) {
          Map<String, dynamic> goodsMap = {
            'widgets_data_id': dataMap['widgets_data_id'],
            'listMap': [],
          };
          state.angleInformationList.add(goodsMap);
        } else {
          var params1 = {
            // 'shop_id': SpUtil.getInt('storeShopNum'),
            // 'super_ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
            "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
            "super_ec_shop_num_id":
                SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
            'item_num_id_list': goodLists,
          };
          Api.shopTag(params1).listen((event) {
            // print(' 商品列表 角标信息  ======================  event = $event');
            if (event['code'] == 0) {
              Map<String, dynamic> goodsMap = {
                'widgets_data_id': dataMap['widgets_data_id'],
                'listMap': event['tag_list'] ?? [],
              };
              state.angleInformationList.add(goodsMap);
            }
            update();
          });
        }
      }
      update();
    });
  }

  void homeCoupon({
    Map<String, dynamic> dataMap,
  }) {
    var map = convert.jsonDecode(dataMap['widgets_data_params']);
    var list = dataMap['style'];
    List styleList = [];
    list.forEach((element) {
      styleList.add(element['style_num_id']);
    });
    if (styleList.length == 0) {
      Map<String, dynamic> goodsMap = {
        'widgets_data_id': dataMap['widgets_data_id'],
        'listMap': [],
      };
      state.couponsList.add(goodsMap);
    } else {
      var params = {
        'usr_num_id': SpUtil.getInt('empeNumId'),
        'activityids': styleList,
      };
      // print('=====----===========-------------  params = $params');
      Api.homeCoupon(params).listen((event) {
        // print('+++++++++++ 优惠券 *********** event = $event');
        if (event['code'] == 0) {
          Map<String, dynamic> goodsMap = {
            'widgets_data_id': dataMap['widgets_data_id'],
            'listMap': event['card_tickets'] ?? [],
          };
          state.couponsList.add(goodsMap);
        }
        update();
      });
    }
  }

  /// 下拉刷新
  void refreshData() {
    signInClick();

    /// 获取店铺ID
    if (state.isChangeShop == 0 &&
        SpUtil.getObject(Config.GET_SHOP_INFO) == null) {
      getAndGoThirdShop();
    }
    state.templateList = [];
    var params = {
      'tmpl_platform_type': '2', //平台:2 APP, 3 小程序
      // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'), //店铺ID
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      'tmpl_type': '1', //页面类型 1频道页 2引导页  3活动页  4广告页  5爆屏页,6 分类页,7 百货页
    };
    Api.homeTemplate(params).listen((event) {
      print('首页 配置信息  event = $event');
      if (event['code'] == 0) {
        // templateList
        if (event['instance'] != null) {
          List list = event['instance']['data'];
          if (event['instance']['data'] != null) {
            List list1 = [];
            for (int i = 0; i < list.length; i++) {
              var map = list[i];
              if (map['widgets_data_status'] == 1) {
                list1.add(map);
              }
            }
            state.templateList = list1;

            processingList();
          } else {
            state.templateList = [];
          }
        } else {
          toast('门店没有数据');
        }
      }
      state.refreshController.refreshCompleted();
      update();
    });
  }

  /// 添加购物车
  void addShoppingCart({
    String ec_shop_num_id,
    String item_num_id,
    String style_num_id,
    String ec_style_num_id,
  }) {
    var params = {
      "use_platform": 2, //平台
      "usr_num_id": SpUtil.getInt('empeNumId'), //会员ID
      "emp_num_id": 0, //操作员ID,移动端无属性,默认传0
      "channel_num_id": 99, //订单渠道：小程序 98，App 99
      "quantity": 1.0, //数量
      // "ec_shop_num_id": ec_shop_num_id, //店铺编码
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      "item_num_id": item_num_id, //商品编码
      "style_num_id": style_num_id, //款式编码
      "ec_style_num_id": ec_style_num_id, //款式唯一编码
      'access_token': SpUtil.getString('token'),
      // "prv_num_id": 320000, //省编码
      // "city_num_id": 320500, //市编码
      // "city_area_num_id": 320583, //区编码
    };
    Api.addShoppingCart(params).listen((event) {
      if (event['code'] == 0) {
        mainLogic.getCartNum();
        toast('添加成功');
      } else {
        toast(event['message']);
      }
    });
  }

  void onTabChange(int index) {
    state.index = index;
    update();
  }

  /// 申请权限
  void requestPermission() async {
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      print("定位权限申请通过");
    } else {
      print("定位权限申请不通过");
    }
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    /// 获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      /// 已经授权
      return true;
    } else {
      //如果客户拒绝过一次，则不再申请权限
      if (SpUtil.getBool('Permissionlocationstatus') == true) {
        return false;
      }

      /// 未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        SpUtil.putBool('Permissionlocationstatus', true);
        return false;
      }
    }
  }

  /// 开始定位
  void startLocation() {
    if (null != _locationPlugin) {
      ///开始定位之前设置定位参数
      _setLocationOption();
      isPositioning.value = true;
      update();
      _locationPlugin.startLocation();
    }
  }

  ///设置定位参数
  void _setLocationOption() {
    if (null != _locationPlugin) {
      AMapLocationOption locationOption = new AMapLocationOption();

      ///是否单次定位
      locationOption.onceLocation = true;

      ///是否需要返回逆地理信息
      locationOption.needAddress = true;

      ///逆地理信息的语言类型
      locationOption.geoLanguage = GeoLanguage.DEFAULT;
      locationOption.desiredLocationAccuracyAuthorizationMode =
          AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;
      locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

      ///设置Android端连续定位的定位间隔
      locationOption.locationInterval = 2000;

      ///设置Android端的定位模式<br>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      ///设置iOS端的定位最小更新距离<br>
      locationOption.distanceFilter = -1;

      ///设置iOS端期望的定位精度
      locationOption.desiredAccuracy = DesiredAccuracy.Best;

      ///设置iOS端是否允许系统暂停定位
      locationOption.pausesLocationUpdatesAutomatically = false;

      ///将定位参数设置给定位插件
      _locationPlugin.setLocationOption(locationOption);
    }
  }

  /// 设置用户选择的位置信息，默认是用户周边位置信息的第一条
  void setUserSelectAddress(Map address) {
    locationResult["userSelectAddress"] = address;
    // print("设置用户选择的位置信息，用户位置是：$locationResult");
    update();
    SpUtil.putObject(Config.USER_CURRENT_LOCATION, locationResult);
  }

  // 设置为当前位置
  void setCurrentPositionClick() {
    locationResult.remove('userSelectAddress');
    print('设置为当前位置 设置为当前位置 locationResult = $locationResult');
    update();
    SpUtil.putObject(Config.USER_CURRENT_LOCATION, locationResult);
  }

  /// 周边搜索
  void surroundingSearch(String keywords) {
    Map<String, dynamic> params = {
      "use_platform": 2,
      "maplocation_x": locationResult["longitude"],
      "maplocation_y": locationResult["latitude"],
      "city": locationResult["city"],
      "key_words": keywords
    };
    Api.surroundingSearch(params).listen((event) {
      print("周边搜索==========$event");
      if (event["code"] == 0 && event["address_list"] != null) {
        List addressList = event["address_list"];
        if (addressList.length > 0 && locationResult["userAddress"] == null) {
          locationResult["defaultAddress"] = addressList.first;
        }
      }
      update();
    });
  }

  /// 获取用户位置信息简要描述
  String getCurrentLocationDescription() {
    Map locationMap = SpUtil.getObject(Config.USER_CURRENT_LOCATION);
    String addressResult = "定位失败";
    if (isPositioning.value == true) {
      addressResult = "正在定位...";
    } else {
      if (locationMap == null || locationMap.length == 0) {
        addressResult = "定位失败";
      } else {
        if (locationMap["userSelectAddress"] == null ||
            locationMap["userSelectAddress"].length == 0) {
          if (locationMap["AMapResult"] == null ||
              locationMap["AMapResult"].length == 0) {
            addressResult = "定位失败";
          } else {
            if (locationMap["AMapResult"]["street"] != null) {
              addressResult = locationMap["AMapResult"]["street"];
            } else {
              if (locationMap["AMapResult"]["district"] != null) {
                addressResult = locationMap["AMapResult"]["district"];
              } else if (locationMap["AMapResult"]["city"] != null) {
                addressResult = locationMap["AMapResult"]["city"];
              } else {
                addressResult = "定位失败";
              }
            }
          }
        } else {
          if (locationMap["userSelectAddress"]["adr"] == null) {
            if (locationMap["userSelectAddress"]["name"] == null) {
            } else {
              addressResult = locationMap["userSelectAddress"]["name"];
            }
          } else {
            addressResult = locationMap["userSelectAddress"]["adr"];
          }
        }
      }
    }
    return addressResult;
  }

  /// 获得高德定位位置信息城市描述
  String getAMapLocationCityName() {
    String addressResult = "定位失败";
    if (isPositioning.value == true) {
      addressResult = "正在定位...";
    } else {
      if (locationResult == null || locationResult.length == 0) {
        addressResult = "定位失败";
      } else {
        if (locationResult["AMapResult"] == null) {
          addressResult = "定位失败";
        } else {
          addressResult = locationResult["AMapResult"]["city"] ?? "定位失败";
        }
      }
    }
    return addressResult;
  }

  /// 获得高德定位完整位置信息描述
  String getAMapLocationAddress() {
    String addressResult = "定位失败";
    if (isPositioning.value == true) {
      addressResult = "正在定位...";
    } else {
      if (locationResult == null || locationResult.length == 0) {
        addressResult = "定位失败";
      } else {
        if (locationResult["AMapResult"] == null) {
          addressResult = "定位失败";
        } else {
          addressResult = locationResult["AMapResult"]["address"] ?? "定位失败";
        }
      }
    }
    return addressResult;
  }

  /// 店铺收藏
  void getFavoriteShopAdd(shopId) {
    var params = {
      'ec_shop_num_id': shopId,
      'usr_num_id': SpUtil.getInt('empeNumId'),
    };
    Api.favoriteShopAdd(params).listen((event) {
      if (event['code'] == 0) {
        state.isFavoriteShop = !state.isFavoriteShop;
        toast('已收藏');
        update();
      } else {
        toast(event['message']);
      }
    });
  }

  /// 取消店铺收藏
  void getFavoriteShopRemove(shopId) {
    var params = {
      'ec_shop_num_id': shopId,
      'usr_num_id': SpUtil.getInt('empeNumId'),
    };
    Api.favoriteShopRemove(params).listen((event) {
      if (event['code'] == 0) {
        state.isFavoriteShop = !state.isFavoriteShop;
        toast('已取消收藏');
        update();
      } else {
        toast(event['message']);
      }
    });
  }

  // 获取收藏店铺列表
  void getColoectShopList() {
    var params = {
      'page': 1,
      'page_size': 100,
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };
    Api.goCollectShopDetail(params).listen((event) {
      if (event['code'] == 0 && event['favorite_shop_list'] != null) {
        state.shopCollectLists = event['favorite_shop_list'];
        event['favorite_shop_list'].forEach((item) {
          if (item['ec_shop_num_id'] ==
              SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id']) {
            state.isFavoriteShop = true;
          }
        });
      } else {
        state.shopCollectLists = [];
      }
      update();
    });
  }

  /// 返回商城
  void getAndGoThirdShop({bool goMain = false}) {
    var params = {
      "data_sign": 0,
      "channel_num_id": 99,
      "use_platform": 2,
      "access_token": SpUtil.getString("token"),
      "ec_shop_num_id": SpUtil.getInt('storeShopNum'),
    };
    Api.getShopInfo(params).listen((event) {
      if (event != null && event['code'] == 0) {
        if (event['ec_shop_infos'].length > 0) {
          SpUtil.remove(Config.GET_SHOP_INFO);
          var shoplistes = event['ec_shop_infos'];
          SpUtil.putObject(Config.GET_SHOP_INFO, {
            'shop_name': shoplistes[0]['ec_shop_name'],
            'shop_id': shoplistes[0]['ec_shop_num_id'],
            'super_ec_shop_num_id': shoplistes[0]['super_ec_shop_num_id'],
            'is_get_home': shoplistes[0]['is_get_home'],
            'is_express': shoplistes[0]['is_express'],
            'service_telphone': shoplistes[0]['service_telphone'],
            'is_pick_up': shoplistes[0]['is_pick_up'],
            'adr': shoplistes[0]['adr'],
            'telphone': shoplistes[0]['telphone'],
            'pickAdrId': shoplistes[0]['sub_unit_num_id'],
            'offShopName': shoplistes[0]['sub_unit_name'],
            'offShopadr': shoplistes[0]['sub_unit_adr'],
            'sub_unit_num_id': shoplistes[0]['sub_unit_num_id'],
            'isSupporySacn': true,
            'free_start_time': '1970-01-01' + shoplistes[0]['free_start_time'],
            'is_express_shops':
                shoplistes[0]['cloud_ec_shop_num_id'] == 1 ? true : false,
            'prv_num_id': shoplistes[0]['prv_num_id'],
            'prv_name': shoplistes[0]['prv_name'],
            'city_num_id': shoplistes[0]['city_num_id'],
            'city_name': shoplistes[0]['city_name'],
            'city_area_num_id': shoplistes[0]['city_area_num_id'],
            'city_area_name': shoplistes[0]['city_area_name'],
            'ec_shop_logo': shoplistes[0]['ec_shop_logo']
          });
          SpUtil.putInt(Config.IS_CHANGE_SHOP, 0);
          if (goMain) {
            Get.offAllNamed(RouteConfig.main,
                arguments: {'isChangeShop': true});
            SpUtil.remove('template_num_id');
          } else {
            Get.forceAppUpdate();
          }
        }
      } else {
        if (event != null) {
          toast(event['massage'] ?? '');
        }
      }
    });
  }

  void getCouponOrToCouponGoodsList({
    Map<String, dynamic> couponModel,
  }) {
    var couponId = couponModel['linktarget'];
    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'activityids': [
        couponId,
      ],
    };
    // print('=====----===========-------------  params = $params');
    Api.homeCoupon(params).listen((event) {
      // print('+++++++++++ 优惠券 *********** event = $event');
      if (event['code'] == 0 &&
          event['card_tickets'] != null &&
          event['card_tickets'].length == 1) {
        var model = event['card_tickets'][0];
        if (model['relation'] == 0) {
          if (model['stock_qty'] > 0) {
            var params = {
              'use_platform': 2,
              'coupon_num_id': model['series'].toString(),
              'usr_num_id': SpUtil.getInt('empeNumId'),
              'access_token': SpUtil.getString('token'),
              'qsource': 301,
              'relation_indate': "永久有效",
              'user_num_id': SpUtil.getInt('empeNumId'),
            };
            Api.getCoupon(params).listen((event) {
              if (event['code'] == 0) {
                toast('领券成功');
                model['relation'] = 1;
              }
            });
          } else {
            toast('库存不足');
          }
        } else {
          if (model['use_begin_date'] != '' &&
              model['use_begin_end'] != '' &&
              model['use_begin_date'] != null &&
              model['use_begin_end'] != null) {
            var startDate = DateTime.tryParse(model['use_begin_date']);
            var endDate = DateTime.tryParse(model['use_begin_end']);
            var disable = (DateTime.now().isBefore(startDate)) ||
                (DateTime.now().isAfter(endDate));
            if (disable) {
              toast('未到优惠券使用时间');
              return false;
            }
          }
          Get.toNamed(RouteConfig.couponGoodsList, arguments: {
            'coupon_id': model['series'],
          });
        }
      }
      update();
    });
  }
}
